//
//  YJYBannerView.m
//  BannerViewDemo
//
//  Created by BaizYi on 2018/10/31.
//  Copyright © 2018 BaizYi. All rights reserved.
//

#import "YJYBannerView.h"
#import "UIView+Frame.h"
#import "RMImageBrowser.h"

@interface YJYBannerView ()<UIScrollViewDelegate>

@property(strong,nonatomic) UIScrollView  *scrollView;
@property(strong,nonatomic) UIPageControl  *pageControl;
@property(strong,nonatomic) UIImageView  *leftImageView;
@property(strong,nonatomic) UIImageView  *rightImageView;
@property(strong,nonatomic) UIImageView  *middleImageView;
@property(assign,nonatomic) NSInteger currentIndex;

@property(strong,nonatomic) NSTimer  *scrollTimer;

@property(assign,nonatomic) NSTimeInterval scrollDuration;




@end

@implementation YJYBannerView

-(instancetype)initWithImageArr:(NSMutableArray *)imageArr frame:(CGRect)frame{
    if (self = [super initWithFrame:frame]) {
        self.imageList = imageArr.copy;
        self.backgroundColor = [UIColor whiteColor];
        [self setupViews];
        self.scrollTimer = [NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(scrollTimeDidFired:) userInfo:nil repeats:YES];
        
        [[NSRunLoop currentRunLoop] addTimer:self.scrollTimer forMode:NSRunLoopCommonModes];
    }
    return self;
}
-(instancetype)initWithImageUrl:(NSMutableArray *)imageUrlArr frame:(CGRect)frame{
    if (self = [super initWithFrame:frame]) {
        [self setupViews];
    }
    return self;
}

-(void)setupViews{
    [self.scrollView addObserver:self forKeyPath:@"contentOffset" options:NSKeyValueObservingOptionNew context:nil];
    [self.scrollView addSubview:self.leftImageView];
    [self.scrollView addSubview:self.middleImageView];
    [self.scrollView addSubview:self.rightImageView];
    [self addSubview:self.scrollView];
    [self addSubview:self.pageControl];
    
    [self placeSubViews];
}

-(void)placeSubViews{
    self.scrollView.frame = self.bounds;
    self.pageControl.frame = CGRectMake(0, self.height-30, self.width, 30);
    self.pageControl.numberOfPages = self.imageList.count;
    CGFloat imageWidth = CGRectGetWidth(self.scrollView.frame);
    CGFloat imageHeight = CGRectGetHeight(self.scrollView.frame);
    self.leftImageView.frame   = CGRectMake(imageWidth * 0, 0, imageWidth, imageHeight);
    self.middleImageView.frame = CGRectMake(imageWidth * 1, 0, imageWidth, imageHeight);
    self.rightImageView.frame  = CGRectMake(imageWidth * 2, 0, imageWidth, imageHeight);
    self.scrollView.contentSize = CGSizeMake(imageWidth * 3, 0);
    
    [self setScrollViewContentOffsetCenter];
}

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
    if ([keyPath isEqualToString:@"contentOffset"]) {
        [self caculateCurrentIndex];
    }
}

-(void)setScrollViewContentOffsetCenter{
    self.scrollView.contentOffset = CGPointMake(CGRectGetWidth(self.scrollView.frame), 0);
}

//计算currentIndex
-(void)caculateCurrentIndex{
    
    if (self.imageList && self.imageList.count) {
        CGFloat pointX = self.scrollView.contentOffset.x;
        
        CGFloat criticalValue = 0.2f;
        if (pointX > 2 * CGRectGetWidth(self.scrollView.frame) - criticalValue) {
            self.currentIndex = (self.currentIndex + 1) % self.imageList.count;
        }else if (pointX < criticalValue){
            if (self.currentIndex == 0) {
                self.currentIndex = 0;
            }else{
                self.currentIndex = (self.currentIndex + self.imageList.count - 1) % self.imageList.count;
            }
        }else{
        }
    }
}

//赋值currentIndex, 同时赋值图片
-(void)setCurrentIndex:(NSInteger)currentIndex{
    if (_currentIndex >= 0) {
        _currentIndex = currentIndex;
        
        NSInteger imageCount = self.imageList.count;
        NSInteger leftIndex = (currentIndex + imageCount - 1) % imageCount;
        NSInteger rightIndex = (currentIndex + 1) % imageCount;
        
        if ([[self.imageList firstObject] isKindOfClass:[NSString class]]) {
            self.leftImageView.image = [UIImage imageNamed:self.imageList[leftIndex]];
            self.middleImageView.image = [UIImage imageNamed:self.imageList[currentIndex]];
            self.rightImageView.image = [UIImage imageNamed:self.imageList[rightIndex]];
        }else if ([[self.imageList firstObject] isKindOfClass:[UIImageView class]]){
            self.leftImageView.image = (UIImage *)[self.imageList[leftIndex] image];
            self.middleImageView.image = (UIImage *)[self.imageList[currentIndex] image];
            self.rightImageView.image = (UIImage *)[self.imageList[rightIndex] image];
        }
        
        [self setScrollViewContentOffsetCenter];
        self.pageControl.currentPage = currentIndex;
    }
}

-(void)layoutSubviews{
    [super layoutSubviews];
    [self placeSubViews];
}


-(void)scrollTimeDidFired:(NSTimer *)timer{
    
    CGFloat criticalValue = .2f;
    if (self.scrollView.contentOffset.x < CGRectGetWidth(self.scrollView.bounds) - criticalValue || self.scrollView.contentOffset.x > CGRectGetWidth(self.scrollView.bounds) + criticalValue) {
        [self setScrollViewContentOffsetCenter];
    }
    CGPoint newOffset = CGPointMake(self.scrollView.contentOffset.x + CGRectGetWidth(self.scrollView.frame), self.scrollView.contentOffset.y);
    [self.scrollView setContentOffset:newOffset animated:YES];
}

-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{

}




-(UIScrollView *)scrollView{
    if (_scrollView == nil) {
        _scrollView = [UIScrollView new];
        _scrollView.delegate = self;
        _scrollView.pagingEnabled = YES;
        _scrollView.showsVerticalScrollIndicator = NO;
        _scrollView.showsHorizontalScrollIndicator = NO;
    }
    return _scrollView;
}
-(UIPageControl *)pageControl{
    if (_pageControl == nil) {
        _pageControl = [UIPageControl new];
        _pageControl.pageIndicatorTintColor = [UIColor lightGrayColor];
        _pageControl.currentPageIndicatorTintColor = [UIColor orangeColor];
    }
    return _pageControl;
}
-(UIImageView *)leftImageView{
    if (_leftImageView == nil) {
        _leftImageView = ({
            UIImageView *imageView = [UIImageView new];
            imageView.contentMode = UIViewContentModeScaleAspectFill;
            imageView;
        });
    }
    return _leftImageView;
}
-(UIImageView *)middleImageView{
    if (_middleImageView == nil) {
        _middleImageView = ({
            UIImageView *imageView = [UIImageView new];
            imageView.contentMode = UIViewContentModeScaleAspectFill;
            imageView.userInteractionEnabled = YES;
            UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(onTap:)];
            [imageView addGestureRecognizer:tap];
            imageView;
        });
    }
    return _middleImageView;
}
-(UIImageView *)rightImageView{
    if (_rightImageView == nil) {
        _rightImageView = ({
            UIImageView *imageView = [UIImageView new];
            imageView.contentMode = UIViewContentModeScaleAspectFill;
            imageView;
        });
    }
    return _rightImageView;
}

-(void)onTap:(UIGestureRecognizer *)tap{
    if ([self.delegate respondsToSelector:@selector(bannerView:selectAtIndex:)]) {
        [self.delegate bannerView:self selectAtIndex:self.currentIndex];
//        [RMImageBrowser showImage:(UIImageView *)tap.view];
    }
}


/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
